<template>
    <div ref="cont" :style="{ width: width, height: realHeight }"></div>
</template>

<script>
import * as echarts from "echarts";

const { info } = console;

export default {
    props: {
        width: {
            default: "600px",
        },
        height: {
            default: "400px",
        },
        title: String,
        xaxis: Object,
        yaxis: Object,
        series: Array,
        tooltip: Object,
        legend: Object,
        grid: Object,
        toolbox: Object,
        darkTheme:{
            type:Boolean,
            default:false
        }
    },
    watch: {
        title() {
            this.reChart();
        },
        xaxis() {
            this.reChart();
        },
        series() {
            this.reChart();
        },
       
        width() {
            this.$nextTick((_) => {
                this.chart.resize();
            });
        },
        height() {
            this.$nextTick((_) => {
                this.chart.resize();
            });
        },
    },
    computed: {
        realHeight() {
            /**
             * 高度支持%
             */
            if (this.height.endsWith("%")) {
                let cont = this.$refs["cont"];
                if (cont) {
                    return this.computeHeight(cont);
                } else {
                    this.$nextTick((_) => {
                        cont = this.$refs["cont"];
                        cont.style.height = this.computeHeight(cont);
                        this.chart.resize();
                    });
                    return "auto";
                }
            } else {
                return isNaN(this.height) ? this.height : this.height + "px";
            }
        },
    },
    methods: {
        computeHeight(cont) {
            let p = cont;
            while ((p = p.parentNode) && p.clientHeight === 0) {}
            let height = (p.clientHeight * this.height.replace("%", "")) / 100;
            return height + "px";
        },

        reChart(cb) {
            const chart = this.chart || (this.chart = echarts.init(this.$refs["cont"],this.darkTheme?'dark':''));
            const options = {
                title: { text: this.title },
                tooltip: {},
                xAxis: this.xaxis || {},
                yAxis: this.yaxis || {},
                series: this.series,
            };

            this.tooltip && (options.tooltip = this.tooltip);
            this.legend && (options.legend = this.legend);
            this.grid && (options.grid = this.grid);
            this.toolbox && (options.toolbox = this.toolbox);

            if (this.addOptions) {
                this.addOptions(options);
            }
           
            chart.setOption(options);
            cb && cb();
        },
    },

    mounted() {
        this.reChart(() => {
             this.chart.resize();
        });
    },
};
</script>
